package cn.operation.api.rest;


import cn.operation.api.dto.CodeDTO;
import cn.operation.api.dto.WayBillDetailDTO;
import cn.operation.backend.enums.DataTypeEnum;
import cn.operation.backend.enums.MessageCodeEnum;
import cn.operation.backend.service.ItfLatestCodePondService;
import cn.operation.backend.service.WayBillService;
import cn.operation.backend.util.BusinessException;
import cn.operation.backend.util.ResultDTOWithPagination;
import cn.operation.base.model.ItfLatestCodePond;
import cn.operation.base.model.WaybillDO;
import com.alibaba.fastjson.JSONArray;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * @FileName:
 * @Description: 运单接口
 * @author: Felix
 * @date: 2017/8/29
 */
@Controller
@RequestMapping(value = "/api/waybill", produces = MediaType.APPLICATION_JSON_VALUE)
@Api(value = "/waybill", description = "运单接口")
public class WayBillRest {

	@Autowired
	private WayBillService wayBillService;
	@Autowired
	private ItfLatestCodePondService itfLatestCodePondService;

	private static final Logger LOGGER = LoggerFactory.getLogger(WayBillRest.class);

	/**
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getWaybillCodes", method = RequestMethod.GET)
	@ApiOperation(value = "查询慧运车最新被修改的运单号列表。", notes = "查询慧运车最新被修改的运单号列表。", produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public ResultDTOWithPagination<List<CodeDTO>> getWaybillCodes() throws Exception {
		LOGGER.info("WayBillRest.getWaybillCodes params : {}");
		ResultDTOWithPagination<List<CodeDTO>> result = new ResultDTOWithPagination<List<CodeDTO>>(true, null, "查询成功");
		try {
			List<ItfLatestCodePond> dataList = itfLatestCodePondService.queryCodes(DataTypeEnum.WAY_BILL.getValue());
			List<CodeDTO> list = new ArrayList<>();
			dataList.stream().forEach(i -> {
				CodeDTO dto = new CodeDTO();
				dto.setCode(i.getCode());
				list.add(dto);
			});
			result.setData(list);
			result.setMessageCode(MessageCodeEnum.SUCCESS.getValue());
		} catch (Exception e) {
			LOGGER.error("WayBillRest.getWaybillCodes error: {}", e);
			result.setMessageCode(MessageCodeEnum.SERVER_ERROR.getValue());
			throw new BusinessException(e.getMessage());
		}
		return result;
	}

	/**
	 * @param waybillCode
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getWaybillDetail", method = RequestMethod.POST)
	@ApiOperation(value = "根据运单号，获取运单明细信息。", notes = "根据运单号，获取运单明细信息。", produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public ResultDTOWithPagination<WayBillDetailDTO> getWaybillDetail(@ApiParam(value = "运单号", required = true) @RequestParam("waybillCode") String waybillCode) throws Exception {
		LOGGER.info("WayBillRest.getWaybillDetail params : {}");
		ResultDTOWithPagination<WayBillDetailDTO> result = new ResultDTOWithPagination<WayBillDetailDTO>(true, null, "查询成功");
		try {
			WayBillDetailDTO dto = new WayBillDetailDTO();
			WaybillDO waybillDO = wayBillService.queryByWaybillCode(waybillCode);
			BeanUtils.copyProperties(waybillDO, dto);
			dto.setCarNumber("慧运车001");
			result.setData(dto);
			result.setMessageCode(MessageCodeEnum.SUCCESS.getValue());
		} catch (Exception e) {
			LOGGER.error("WayBillRest.getWaybillDetail error: {}", e);
			result.setMessageCode(MessageCodeEnum.SERVER_ERROR.getValue());
			throw new BusinessException(e.getMessage());
		}
		return result;
	}

	/**
	 * @param waybillCode
	 * @param shipToDate
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/submitShipTo", method = RequestMethod.POST)
	@ApiOperation(value = "根据运单号更新运单运抵状态。", notes = "根据运单号更新运单运抵状态。", produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public ResultDTOWithPagination<Object> submitShipTo(@ApiParam(value = "运单号", required = true) @RequestParam("waybillCode") String waybillCode,
														@ApiParam(value = "运抵日期,例：2017-8-30", required = true) @RequestParam("shipToDate") String shipToDate,
														@ApiParam(value = "服务订单号", required = true) @RequestParam("serviceOrderCode") String serviceOrderCod) throws Exception {
		LOGGER.info("WayBillRest.submitShipTo params : {}");
		ResultDTOWithPagination<Object> result = new ResultDTOWithPagination<Object>(true, null, "更新成功");
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		try {
			wayBillService.updateShipTo(waybillCode, format.parse(shipToDate));
			result.setMessageCode(MessageCodeEnum.SUCCESS.getValue());
		} catch (Exception e) {
			LOGGER.error("WayBillRest.submitShipTo error: {}", e);
			result.setMessageCode(MessageCodeEnum.SERVER_ERROR.getValue());
			throw new BusinessException(e.getMessage());
		}
		return result;
	}

	/**
	 * @param waybillCode
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/addWayBill", method = RequestMethod.POST)
	@ApiOperation(value = "运单放入单据池。", notes = "运单放入单据池。", produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public ResultDTOWithPagination<Object> addWayBill(@ApiParam(value = "运单号", required = true) @RequestParam("waybillCode") String waybillCode) throws Exception {
		LOGGER.info("WayBillRest.addWayBill params : {}");
		ResultDTOWithPagination<Object> result = new ResultDTOWithPagination<Object>(true, null, "添加成功");
		try {
			itfLatestCodePondService.addCode(waybillCode, DataTypeEnum.WAY_BILL.getValue());
			result.setMessageCode(MessageCodeEnum.SUCCESS.getValue());
		} catch (Exception e) {
			LOGGER.error("WayBillRest.addWayBill error: {}", e);
			result.setMessageCode(MessageCodeEnum.SERVER_ERROR.getValue());
			throw new BusinessException(e.getMessage());
		}
		return result;
	}

	/**
	 * @param serviceOrders
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/addServiceOrders", method = RequestMethod.POST)
	@ApiOperation(value = "服务订单放入单据池。", notes = "服务订单放入单据池。", produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public ResultDTOWithPagination<Object> addServiceOrder(@ApiParam(value = "运单号", required = true) @RequestParam("serviceOrders") String serviceOrders) throws Exception {
		LOGGER.info("WayBillRest.addServiceOrders params : {}");
		ResultDTOWithPagination<Object> result = new ResultDTOWithPagination<Object>(true, null, "添加成功");
		try {
			List<String> list = JSONArray.parseArray(serviceOrders, String.class);
			list.stream().forEach(str -> {
				try {
					itfLatestCodePondService.addCode(str, DataTypeEnum.SERVICE_ORDER.getValue());
				} catch (Exception e) {
					LOGGER.error("WayBillRest.addServiceOrders error: {}", e);
				}
			});
			result.setMessageCode(MessageCodeEnum.SUCCESS.getValue());
		} catch (Exception e) {
			LOGGER.error("WayBillRest.addServiceOrders error: {}", e);
			result.setMessageCode(MessageCodeEnum.SERVER_ERROR.getValue());
			throw new BusinessException(e.getMessage());
		}
		return result;
	}
}
